import dash
import requests
from dash import html, dcc
import feffery_antd_components as fac
from dash.dependencies import Input, Output, State

app = dash.Dash(
    __name__,
    suppress_callback_exceptions=True
)


app.layout = html.Div(
    [
        dcc.Interval(
            id='interval',
            interval=3000
        ),

        fac.AntdButton(
            '创建新任务',
            id='create-new-task',
            type='primary'
        ),

        fac.AntdDivider(isDashed=True),

        html.Div(id='all-tasks-info')
    ],
    style={
        'width': '1000px',
        'margin': '0 auto',
        'paddingTop': '100px'
    }
)

@app.callback(
    Output('all-tasks-info', 'children'),
    [Input('interval', 'n_intervals'),
    Input('create-new-task', 'nClicks')]
)
def show_all_tasks_info(n_intervals, nClicks):

    if dash.ctx.triggered_id == 'create-new-task':
        _ = (
            requests
            .get('http://127.0.0.1:8000/create-new-task')
        )

    # 获取全部任务id信息
    all_tasks_id = (
        requests
        .get(
            'http://127.0.0.1:8000/get-all-tasks-id'
        )
        .json()
    )

    # 根据任务id列表查询相应的任务信息
    tasks_info = (
        requests
        .post(
            'http://127.0.0.1:8000/get-tasks-info',
            json={
                'task_id_list': all_tasks_id['data']
            }
        )
        .json()
    )

    return fac.AntdTable(
        columns=[
            {
                'dataIndex': 'task_id',
                'title': 'task_id',
                'width': '33.33%'
            },
            {
                'dataIndex': 'create_datetime',
                'title': 'create_datetime',
                'width': '33.33%'
            },
            {
                'dataIndex': 'task_progress',
                'title': 'task_progress',
                'renderOptions': {
                    'renderType': 'mini-ring-progress'
                },
                'width': '33.33%'
            },
        ],
        data=tasks_info['task_info'],
        bordered=True,
        miniChartHeight=70
    )


if __name__ == '__main__':
    app.run(debug=True)